import React, {PureComponent} from 'react';
import {View, Animated, Button, ToastAndroid} from 'react-native';

export default class TestAnimationNative extends PureComponent {
  opacity = new Animated.Value(0); // Animated.Value 托管到 UI 线程
  scale = new Animated.Value(0);

  // 模拟 JS 被占用
  blockJS = () => {
    const start = Date.now();
    ToastAndroid.show('开始阻塞', 0.5);
    while (Date.now() - start < 1000) {
      // 空循环，占用 1000ms JS
    }
    ToastAndroid.show('结束阻塞', 0.5);
  };

  runAnimation = () => {
    // 并行动画
    Animated.parallel([
      Animated.timing(this.opacity, {
        toValue: 1,
        duration: 1000,
        useNativeDriver: true, // 🔑 动画在 UI 线程执行
      }),
      Animated.timing(this.scale, {
        toValue: 1,
        duration: 1000,
        useNativeDriver: true,
      }),
    ]).start();
  };

  startAnimation = () => {
    setTimeout(() => {
      this.blockJS();
    }, 500);
    this.runAnimation();
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <Animated.View
          style={{
            width: 200,
            height: 200,
            backgroundColor: 'blue',
            opacity: this.opacity,
            transform: [{scale: this.scale}],
          }}
        />
        <Button title="开始动画" onPress={this.startAnimation} />
        <Button title="模拟JS阻塞" onPress={this.blockJS} />
      </View>
    );
  }
}
